package cn.com.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import cn.com.BaseActivity;
import cn.com.R;
import cn.com.TabHostMain;
import cn.com.adapter.ChatMsgViewAdapter;
import cn.com.domain.ChartMsgEntity;
import cn.com.util.MyToast;
/**
 * 单个聊天
 * @author ChonZY
 */
public class ChartActivity extends BaseActivity implements OnClickListener ,OnLongClickListener{
	private static final int FINISH_RECORD_HINT = 10;
	protected static final int FINISH_RECORD_START = 11;
	protected static final int FINISH_RECORD_STOP = 12;
	private boolean isOpen = true ; //控制显示 键盘 或录音
	private Button btn_keyRecord; // 键盘 或录音
	private EditText et_sendMsg ; 
	private Button btn_recordMsg ; // 录音
	private RelativeLayout rl_record_hint; // 中部短暂录音提示
	
	private MediaRecorder mRecorder; // 录音
	private String saveRecoardDir; // 保存录音的路径
	boolean longClicked = false;  // 长按 or 松开
	
	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case FINISH_RECORD_HINT: // 单击事件完成录音提示
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				rl_record_hint.setVisibility(View.GONE);
				break;
				
				
			case  FINISH_RECORD_START:
				
				// 录音前 ，先检测sd卡 是否可用
				String sdStatus = Environment.getExternalStorageState() ;
				if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
					MyToast.getToast(ChartActivity.this, "SD卡不可用，请检查SD卡").show();
					return ;
				}
				saveRecoardDir = Environment.getExternalStorageDirectory()+"/vmRecord/".trim();
				
				File dir = new File(saveRecoardDir);

				if (!dir.exists()) {
					dir.mkdir(); // 创建文件夹
				}
				
				System.out.println("录音文件路径:"+ saveRecoardDir);
				mRecorder = new MediaRecorder();                                              // 创建录音工具对象
				mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);                      // 设置声音源
				mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);              // 设置输出格式3gp
				mRecorder.setOutputFile(saveRecoardDir+ System.currentTimeMillis()+".3gp");   // 设置输出文件路径
				mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);                 // 设置编码器
				try {
					mRecorder.prepare();                                                      // 准备
				
					mRecorder.start();
					System.out.println("--"+saveRecoardDir+ System.currentTimeMillis()+".3gp");
				} catch (Exception e) {
					e.printStackTrace();
				} 
			
			break ;
			
			case  FINISH_RECORD_STOP:
				if(mRecorder!= null){
					
					try {
						mRecorder.stop();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}         //停止
					mRecorder.release();	  //释放
					mRecorder = null ;        // 垃圾回收
				}
			
			break ;

			}
			
		};
		
	};
	private Button mBtnSend ;
	private EditText mEditTextContent ;
	private ListView mListView ;
	private ChatMsgViewAdapter mAdapter ;
	private List<ChartMsgEntity> mDataArrays = new ArrayList<ChartMsgEntity>();
	
	private String[] msgArray = new String[]{"老王，周末有时间吗？约上老赵老地方聚聚如何？","好主意，有什么地方推荐好玩的吗 ？","上次去的那家KTV不错，要不还去那家吧！","我同意！"};
	private String[]dataArray = new String[]{ "2013-09-10 10:30", 
			"013-09-10 10:32", "013-09-10 10:32", "013-09-10 10:34"}; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.chart);
		init();
		initView();
		
		initData();
		
		btn_recordMsg.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: // 按住事件发生后 执行的代码区域
					System.out.println("常时间按住了");
					
					
					
					Message msg = new Message();
					msg.what = FINISH_RECORD_START;
					mHandler.sendMessage(msg);
					break;
				
				case MotionEvent.ACTION_UP:   //松开事件发生后执行代码的区域
					System.out.println("长按松开！");
					
					Message msg1 = new Message();
					msg1.what = FINISH_RECORD_STOP;
					mHandler.sendMessage(msg1);
					
					
					break ;
				
				}
				return false;
			}
		});
		
		
		
	}
	private final static int COUNT = 4 ;
	private void initData() {
		for(int i = 0 ; i< COUNT ; i++){
			ChartMsgEntity entity = new ChartMsgEntity();
			entity.setDate(dataArray[i]);
			if(i%2 == 0){
				entity.setName("老周");
				entity.setMsgType(true);
			}else{
				entity.setName("老王");
				entity.setMsgType(false);
			}
			entity.setText(msgArray[i]);
			mDataArrays.add(entity);
		}
		
		mAdapter = new ChatMsgViewAdapter(this,mDataArrays);
		mListView.setAdapter(mAdapter);
		
	}
	private void initView() {
		mListView = (ListView) findViewById(R.id.lv_chart);
		mBtnSend = (Button) findViewById(R.id.btn_send);
		mBtnSend.setOnClickListener(this);
		mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
	}
	private void init() {
		//启动activity时不自动弹出软键盘
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
		btn_keyRecord = (Button) findViewById(R.id.btn_chart_keyboad);
		btn_keyRecord.setOnClickListener(openClickListener);
		btn_recordMsg = (Button) findViewById(R.id.btn_recordmessage);
		et_sendMsg = (EditText) findViewById(R.id.et_sendmessage);
		et_sendMsg.setVisibility(View.VISIBLE);
		btn_recordMsg.setOnClickListener(this);
		rl_record_hint = (RelativeLayout) findViewById(R.id.rl_chart_hint);
		rl_record_hint.setVisibility(View.GONE);
		btn_recordMsg.setOnLongClickListener(this);
	}
	// 返回
	public void chat_back(View view){
		Intent intent = new Intent(this,TabHostMain.class);
		startActivity(intent);
		finish();
	}
	
	private OnClickListener openClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// 打开键盘
			if(isOpen){
				btn_keyRecord.setBackgroundResource(R.drawable.chat_bg_keboard);
				et_sendMsg.setVisibility(View.GONE);
				btn_recordMsg.setVisibility(View.VISIBLE);
				isOpen = false ;
			}else{
				btn_keyRecord.setBackgroundResource(R.drawable.chat_change);
				et_sendMsg.setVisibility(View.VISIBLE);
				btn_recordMsg.setVisibility(View.GONE);
				isOpen = true ;
			}
		}
	};

	@Override
	public void onClick(View v) {
		Intent intent = null ;
		switch (v.getId()) {
		//点击 录音 提示 录音时间太短
		case R.id.btn_recordmessage:
			
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					rl_record_hint.setVisibility(View.VISIBLE);
					
				}
			}, 200);
//			Message msg = new Message();
//			msg.what = FINISH_RECORD_HINT;
//			mHandler.sendMessage(msg);
			
			break;
			
		case R.id.btn_send: // 发送消息
			send();
			break ;

		}
	}
	/**
	 * 发消息
	 */
	private void send() {
		String contString = mEditTextContent.getText().toString();
		if(contString.length() >0 ){
			ChartMsgEntity entity  = new ChartMsgEntity();
			entity.setDate(getDate());
			entity.setName("老王");
			
			entity.setMsgType(false);
			entity.setText(contString);
			
			mDataArrays.add(entity);
			mAdapter.notifyDataSetChanged();
			mEditTextContent.setText("");
			mListView.setSelection(mListView.getCount() -1);
		}
	}
	
	private String getDate() {
		Calendar c = Calendar.getInstance();
		String year = String.valueOf(c.get(Calendar.YEAR));
	    String month = String.valueOf(c.get(Calendar.MONTH) + 1);
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(c.get(Calendar.MINUTE));
        
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); 
		return  sbBuffer.toString();
	}
	/**
	 * 长按 录音
	 */
	@Override
	public boolean onLongClick(View v) {
		if(v == btn_recordMsg){ // 当按下的是 按钮时
			longClicked = true ;
			return longClicked;
		}
		return false;
	}
	
	
	
	
	
	
	
	

}
